import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author Created by xqq
 * @Date Created in 22:32 2017/6/5
 */
public class CountDown extends HttpServlet {
    public static final int HEIGHT = 120;  //时钟高度
    public static final int WIDTH =800;   //时钟宽度

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //在内存中创建一张图片
        BufferedImage image = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
        //得到图片
        Graphics g = image.getGraphics();
        // 设置图片的背景色
        setBackGround(g);
        //设置图片边框
        setBorder(g);
        //设置画笔颜色
        g.setColor(Color.BLACK);
        //设置字体：宋体、不带格式的、字号
        g.setFont(new Font("宋体", Font.PLAIN, 30 + 5));
        // 在图片上写上时间
        String Date = getDate();
        g.drawString(Date,(WIDTH / 6)  , 60);
        request.getSession().setAttribute("checkcode", Date); // 将当前时间存在session中

        /*
         * 5.图形写给浏览器
         */
        response.setContentType("image/jpeg");
        // 发响应头控制浏览器不要缓存图片
        response.setDateHeader("expries", -1);
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        ImageIO.write(image, "jpg", response.getOutputStream());
    }
    /**
     * 设置图片边框
    * @Author：season
    * @Description:
    * @Date: 2017/6/6 17:15
    */
    private void setBorder(Graphics g) {
        // 设置边框颜色
        g.setColor(Color.BLUE);
        // 边框区域
        g.drawRect(1, 1, WIDTH-2, HEIGHT-2);

    }
    /**
     * 设置背景颜色
    * @Author：season
    * @Description:
    * @Date: 2017/6/6 17:15
    */
    private void setBackGround(Graphics g) {
        // 设置颜色
        g.setColor(Color.WHITE);
        // 填充区域
        g.fillRect(0, 0, WIDTH, HEIGHT);
    }
    private String getDate (){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String date = new String(df.format(new Date()));// new Date()为获取当前系统时间
        System.out.println(date);
        return date;
    }
}
